import React, {Component} from 'react';

class CartFooter extends Component {
    constructor(props) {
        super(props);
        //从仓库进行操作
        this.state = {
            totalPrice: 0,
            totalNumber: 0
        }
    }

    getNumberAndTotalPrice = () => {
        var totalNumber = 0;

        var totalPrice = this.props.store.getState().reduce((prev, next) => {
            totalNumber += next.number;
            return prev + next.goodsPrice * next.number;
        }, 0);

        this.setState({
            totalPrice,
            totalNumber,
        })


    }

    componentDidMount() {
        // 首次挂载组件的时候也需要从仓库获取最新的数据信息
        this.getNumberAndTotalPrice();

        /*CartFooter也需要订阅一下仓库的最新状态*/
        this.props.store.subscribe(this.getNumberAndTotalPrice)
    }


    render() {
        return (
            <div>
                <h2>CartFooter组件-兄弟关系</h2>
                <p>商品共 {this.state.totalNumber} 件</p>
                <p>商品总价¥： {this.state.totalPrice}</p>
            </div>
        );
    }
}

export default CartFooter;
